﻿using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Iot.RealTimeData.RealTimeData;
using Iot.Shared.Path;
using Microsoft.Extensions.Logging;

namespace Iot.RealTimeData.RealTimeDataEvent;

public sealed class RealTimeData<T, T1>(IOnValueFactory factory, ILogger<RealTimeData<T, T1>> logger)
    : IRealTimeData<T, T1>
    where T1 : IShowValue<T>, ISetValue<T>
{
    /// <summary>
    ///     模拟量保存
    /// </summary>
    private readonly ConcurrentDictionary<DevicePath, T1> _data = [];

    public void Inspection(DateTimeOffset staleBated)
    {
        logger.LogTrace("函数：{函数}，时间{时间}", nameof(Inspection), staleBated);
        Parallel.ForEach(_data.Values, a => a.SetValue(default!, staleBated));
    }

    /// <summary>
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public T1 GetValue(DevicePath path)
    {
        logger.LogTrace("函数：{函数}，路径：{路径}", nameof(GetValue), path);
        lock (_data)
        {
            return _data.GetOrAdd(path, factory.Create<T, T1>);
        }
    }

    public void SetValue(DevicePath path, T value, DateTimeOffset timeStamp)
    {
        if (_data.TryGetValue(path, out var onValue))
        {
            logger.LogTrace("函数：{函数}，路径：{路径}，写入值：{值}，时间{时间}", nameof(SetValue), path, value, timeStamp);
            onValue.SetValue(value, timeStamp);
        }
        else
        {
            logger.LogTrace("函数：{函数}，路径：{路径}，未写入值：{值}，时间{时间}", nameof(SetValue), path, value, timeStamp);
        }
    }
}